<?php

namespace app\admin\controller\auth;
use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\common\controller\Backend;
use fast\Tree;
use think\Cache;
use fast\Random;
use fast\Cols;
use fast\Date;

/**
 * 管理员管理
 *
 * @icon fa fa-users
 * @remark 一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成
 */
class Admin extends Backend
{
    protected $model = null;
    protected $rulelist = [];
    protected $multiFields = 'ismenu,status';
    protected $childrenGroupIds = [];
    protected $childrenAdminIds = [];

    public function initialize()
    {
        parent::initialize();
        $this->model = model('Admin');
        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        //取出当前管理员所拥有权限的分组
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);
        $groupList = collection(AuthGroup::where('itemid', 'in', $this->childrenGroupIds)->select())->toArray();
        Tree::instance()->init($groupList);
        $groupdata = [];
        if ($this->auth->isSuperAdmin()){
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v)
            {
                $groupdata[$v['itemid']] = $v['name'];
            }
        }else{
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n)
            {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['itemid']));
                $temp = [];
                foreach ($childlist as $k => $v)
                {
                    $temp[$v['itemid']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;
            }
            $groupdata = $result;
        }

        $this->view->assign('groupdata', $groupdata);
        $this->assignconfig("admin", ['id' => $this->auth->id]);
    }

    public function index()
    {
        	$columnlist = Cols::columnread('admin');
        	$flag = array();$options = array();
        	foreach($columnlist as $v){
    			     $flag[] = $v['listorder'];
               if($v['options']&&$v['isshowlist']==1){
                  //把带有选项的列，提取出来。
                  $options[$v['columnenname']] = $v['options'];
              }
		      }
		      array_multisort($flag, SORT_ASC, $columnlist);
		      //设置过滤方法
		      $this->request->filter(['strip_tags']);
      		//如果发送的来源是Selectpage，则转发到Selectpage
      		if ($this->request->request('pkey_name')){
      				return $this->selectpage();
      		}
      		$searchfileds = array();
          $searchdefault = array();
  				$searchfileds['username'] = 'varcharshort';
  				list($where, $sort, $order, $offset, $limit) = $this->buildparams($searchfileds);
          $limit = 300;
  				$order = 'desc';
  				$sort = 'createtime';
  				$total = $this->model->where($where)->order($sort, $order)->count();
  				$totalpage = 1;$page = 1;
  				if($limit>0){
  						$totalpage = $total%$limit==0?intval($total/$limit):intval($total/$limit)+1;
  						//总页数
  						if($offset>0){$page = intval($offset/$limit)+1;}
  				}
          //print_r($where);exit;
  				$list = $this->model
  				->where($where)
  				->order($sort, $order)
  				->limit($offset, $limit)
  				->select();

  				for ($i = 0; $i < count($list); $i++) {
  						if(isset($list[$i]['category'])){
  								$list[$i]['catname'] = $list[$i]['category']['name'];
  						}
  						unset($list[$i]['intro']);unset($list[$i]['content']);
              foreach ($options as $k => $v) {
                  if(isset($list[$i][$k])){
                      $arj = json_decode($v,true);
                      $sarj = $arj[$list[$i][$k]];
                      $list[$i][$k] = $sarj;
                  }
              }
              $list[$i]['logintime'] = Date::timetodate($list[$i]['logintime'],3);
  						$list[$i]['createtime'] = Date::timetodate($list[$i]['createtime'],3);
  						$list[$i]['updatetime'] = Date::timetodate($list[$i]['updatetime'],3);
  				}

  				$result = array("total" => $total, "rows" => $list);
  				$this->view->assign("lists",$result['rows']);
          $this->view->assign("listsjson",json_encode($result['rows']));
          $this->view->assign("columnlistjson",json_encode($columnlist));
          $this->view->assign("columnlist",$columnlist);
  				$this->view->assign("total",$result['total']);
  				$this->view->assign("offset",$offset);
  				$this->view->assign("limit",$limit);
  				$this->view->assign("totalpage",$totalpage);
  				$this->view->assign("page",$page);
  				return $this->view->fetch('index');
		}
    //添加
    public function add(){
        if ($this->request->isPost()){
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params){
                  $params['salt'] = Random::alnum();
                  $params['password'] = md5(md5($params['password']) . $params['salt']);
                  $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
                  $params['itemid'] = str_replace('-','',Random::uuid());
                  //print_r($this->request->post("city/a"));exit;
                  $params['province'] = implode(',',$this->request->post("province/a"));
                  $cityarry = $this->request->post("city/a");
                  if($cityarry[0]){
                      $params['city'] = implode(',',$cityarry);
                  }else{
                      $cityarry = model('City')->getCityByProvince($params['province']);

                      $cid = '';
                      foreach ($cityarry as $k => $v) {
                          $cid .= $v['id'].',';
                      }
                      //print_r($cid);exit;
                      $params['city'] = substr($cid,0,strlen($cid)-1);
                  }

                  $result = $this->model->validate('Admin.add')->save($params);
                  if ($result === false){
                      $this->error($this->model->getError());
                  }
                  $group = $this->request->post("group/a");

                  //过滤不允许的组别,避免越权
                  $group = array_intersect($this->childrenGroupIds, $group);
                  $dataset = [];
                  foreach ($group as $value)
                  {
                      $dataset[] = ['uid' => $this->model->itemid, 'group_id' => $value];
                  }
                  model('AuthGroupAccess')->saveAll($dataset);
                  $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }
    //编辑
    public function edit($ids = NULL)
    {
        $row = $this->model->get(['itemid' => $ids]);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params)
            {
                if ($params['password'])
                {
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                }
                else
                {
                    unset($params['password'], $params['salt']);
                }
                //这里需要针对username和email做唯一验证
                $adminValidate = \think\Loader::validate('Admin');
                $adminValidate->rule([
                   'username' => 'require|max:50|unique:admin,username,' . $row->itemid,
                   'email'    => 'require|email|unique:admin,email,' . $row->itemid
                ]);
                $params['province'] = implode(',',$this->request->post("province/a"));
                $cityarry = $this->request->post("city/a");
                if($cityarry[0]){
                    $params['city'] = implode(',',$cityarry);
                }else{
                    $cityarry = model('City')->getCityByProvince($params['province']);

                    $cid = '';
                    foreach ($cityarry as $k => $v) {
                        $cid .= $v['id'].',';
                    }
                    //print_r($cid);exit;
                    $params['city'] = substr($cid,0,strlen($cid)-1);
                }
                $result = $row->validate('Admin.edit')->save($params);
                if ($result === false)
                {
                   $this->error($row->getError());
                }
                // 先移除所有权限
                model('AuthGroupAccess')->where('uid', $row->itemid)->delete();
                $group = $this->request->post("group/a");
                // 过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenGroupIds, $group);
                $dataset = [];
                foreach ($group as $value){
                    $dataset[] = ['uid' => $row->itemid, 'group_id' => $value];
                }
                model('AuthGroupAccess')->saveAll($dataset);
                $this->success();
            }
            $this->error();
        }
        $grouplist = $this->auth->getGroups($row['itemid']);
        $groupids = [];
        foreach ($grouplist as $k => $v)
        {
            $groupids[] = $v['itemid'];
        }
        $citylist = array();
        if($row['city']){
            $citylist = model('City')->where('itemid','in',$row['city'])->order('listorder','desc')->select();
        }
        $this->view->assign("citylist", $citylist);
        $this->view->assign("row", $row);
        $this->view->assign("groupids", $groupids);
        return $this->view->fetch();
    }
    //删除
    public function del($ids = "")
    {
        if ($ids)
        {
            // 避免越权删除管理员
            $childrenGroupIds = $this->childrenGroupIds;
            $adminList = $this->model->where('itemid', 'in', $ids)->where('itemid', 'in', function($query) use($childrenGroupIds) {
                        $query->name('auth_group_access')->where('group_id', 'in', $childrenGroupIds)->field('uid');
                    })->select();
            //print_r($childrenGroupIds);exit;
            if ($adminList)
            {
                $deleteIds = [];
                foreach ($adminList as $k => $v)
                {
                    $deleteIds[] = $v->itemid;
                }
                $deleteIds = array_diff($deleteIds, [$this->auth->itemid]);
                if ($deleteIds)
                {
                    $this->model->destroy($deleteIds);
                    model('AuthGroupAccess')->where('uid', 'in', $deleteIds)->delete();
                    $this->success();
                }
            }
        }
        $this->error();
    }

    /**
     * 批量更新
     * @internal
     */
    public function multi($ids = "")
    {
        // 管理员禁止批量操作
        $this->error();
    }
    /**
     * 选择
     */
    public function select()
    {
        $columnlist = Cols::columnread('admin');
        $flag = array();$options = array();
        foreach($columnlist as $v){
            $flag[] = $v['listorder'];
            if($v['options']&&$v['isshowlist']==1){
                //把带有选项的列，提取出来。
                $options[$v['columnenname']] = $v['options'];
            }
        }
        array_multisort($flag, SORT_ASC, $columnlist);
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('pkey_name')){
            return $this->selectpage();
        }
        $searchfileds = array();
        $searchdefault = array();
        $searchfileds['username'] = 'varcharshort';
        list($where, $sort, $order, $offset, $limit) = $this->buildparams($searchfileds);
        $limit = 300;
        $order = 'desc';
        $sort = 'createtime';
        $total = $this->model->where($where)->order($sort, $order)->count();
        $totalpage = 1;$page = 1;
        if($limit>0){
            $totalpage = $total%$limit==0?intval($total/$limit):intval($total/$limit)+1;
            //总页数
            if($offset>0){$page = intval($offset/$limit)+1;}
        }
        $list = $this->model
        ->where($where)
        ->order($sort, $order)
        ->limit($offset, $limit)
        ->select();
        for ($i = 0; $i < count($list); $i++) {
            if(isset($list[$i]['category'])){
                $list[$i]['catname'] = $list[$i]['category']['name'];
            }
            unset($list[$i]['intro']);unset($list[$i]['content']);
            foreach ($options as $k => $v) {
                if(isset($list[$i][$k])){
                    $arj = json_decode($v,true);
                    $sarj = $arj[$list[$i][$k]];
                    $list[$i][$k] = $sarj;
                }
            }
            $list[$i]['logintime'] = Date::timetodate($list[$i]['logintime'],3);
            $list[$i]['createtime'] = Date::timetodate($list[$i]['createtime'],3);
            $list[$i]['updatetime'] = Date::timetodate($list[$i]['updatetime'],3);
        }

        $result = array("total" => $total, "rows" => $list);
        $this->view->assign("multiple",$this->request->get('multiple'));
        $this->view->assign("lists",$result['rows']);
        $this->view->assign("columnlist",$columnlist);
        $this->view->assign("total",$result['total']);
        $this->view->assign("offset",$offset);
        $this->view->assign("limit",$limit);
        $this->view->assign("totalpage",$totalpage);
        $this->view->assign("page",$page);
        return $this->view->fetch('select');
    }
    /**
     * 下拉搜索
     */
    protected function selectpage()
    {
        $this->dataLimit = 'auth';
        $this->dataLimitField = 'id';
        return parent::selectpage();
    }
}
